﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Reflection;
using System.Text;
using System.Web.Http;
using System.Web.Http.SelfHost;
using Newtonsoft.Json.Converters;

namespace ConsoleWebApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:3333");
            //映射属性路由
            config.MapHttpAttributeRoutes();
            //设置路由
            config.Routes.MapHttpRoute("default", "api/{controller}/{id}", new { id = RouteParameter.Optional });
            //清掉Xml选择器
            config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            //默认返回 json 
            config.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("datatype", "json", "application/json"));
            //可以返回 xml
            config.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("datatype", "xml", "application/xml"));
            //时间序列化设置
            config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new IsoDateTimeConverter
            {
                DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
            });


            var server = new HttpSelfHostServer(config);
            server.OpenAsync().Wait();
            Console.WriteLine("Server is opened");
            JsonSerializer();
            Console.ReadKey();
        }



        /// <summary>
        /// 一个测试
        /// </summary>
        public static void JsonSerializer()
        {
            Newtonsoft.Json.Converters.IsoDateTimeConverter timeConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
            timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            //初始化一个 序列化配置器
            Newtonsoft.Json.JsonSerializerSettings JSS = new Newtonsoft.Json.JsonSerializerSettings();
            //配置序列化规则
            JSS.ContractResolver = new Authorization.HideAttrContractResolver(new String[] { "B" });
            JSS.Converters.Add(timeConverter);
            //Newtonsoft.Json.JsonTextWriter.Indentation
            var s = Newtonsoft.Json.JsonConvert.SerializeObject(new { A = 1, B = 2, C = 3 }, Newtonsoft.Json.Formatting.Indented, JSS);


            Console.WriteLine(s);

        }


    }
}
